from sqlalchemy import Column, Integer, String, \
    Text, ForeignKey, SmallInteger
from sqlalchemy.orm import relationship
from datetime import datetime

from werkzeug.security import generate_password_hash, check_password_hash

from app.models import Base
from app import create_session





class Admin(Base):
    __tablename__ = "admin"
    id = Column(Integer, primary_key=True)
    email = Column(String(24), unique=True, nullable=False)
    nickname = Column(String(24), unique=True)
    auth = Column(SmallInteger, default=9)
    _password = Column('password', String(100))

    role_id = Column(Integer, ForeignKey('role.id')) # 所属角色

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, raw):
        self._password = generate_password_hash(raw)

    def check_password(self, raw):
        if not self._password:
            return False
        return check_password_hash(self._password, raw)

    @staticmethod
    def register(nickname, email, password, role_id):
        admin = Admin()
        admin.nickname = nickname
        admin.email = email
        admin.password = password 
        admin.role_id = role_id
        Session = create_session()  
        with Session() as s:
            s.add(admin)
            s.commit() 

    # @staticmethod
    # def verify(email, password):
    #     user = User.query.filter_by(email=email).first_or_404()
    #     if not user.check_password(password):
    #         raise AuthFailed()
    #     scope = 'AdminScope' if user.auth == 2 else 'UserScope'
    #     return {'uid': user.id, 'scope': scope}

    